#include "lmp_to_db_main.h"
#include "../sql_interface_stub/sql_interface_stub.h"
#include "../pmk_libs_headers/lmpwlib.h"
#include "sql_interface.h"

int dProcessSingleFile(char* psDatabaseDir, char* psLmpFile)
{
    DataBase queries;
    queries.InitDB(psDatabaseDir);
    //Check input
    if ( !psLmpFile )
        return LMP_TO_DB_INVALID_INPUT;

    //Initialization of LMP Class.
    LMP hFileHandler;
    hFileHandler.Init(psLmpFile,REGIMREAD);

    if(hFileHandler.ErrorCode)
    {
    //    printf(LMP_TO_DB_NAME" : INTERNAL_FILE_DESCRIPTOR_ERROR. Code: %d \n", hFileHandler.ErrorCode);
        return LMP_TO_DB_INTERNAL_FILE_DESCRIPTOR_ERROR;
    }

     //Retrieving INFO struct.
    INFO_LMP sInfoLmp;
    bool bRetCode = false;

    bRetCode = hFileHandler.GetInfoLmp(sInfoLmp);

    if(!bRetCode)
    {
       // printf(LMP_TO_DB_NAME" : INTERNAL_FILE_DESCRIPTOR_ERROR. GET INFO. Code: %d \n", hFileHandler.ErrorCode);
        return LMP_TO_DB_INTERNAL_FILE_DESCRIPTOR_ERROR;
    }

    //Pushing into the sql interface
    if(!queries.PushInfoStruct(&sInfoLmp))
        return LMP_TO_DB_INTERNAL_INFO_PUSH_ERROR;


    //Retrieving passport/metrics
    long N_Obj, lRetCode;
    Pasport sPassport;
    POINT_LMP* pMetric = NULL;
    bRetCode = true;

    pMetric = new POINT_LMP[sInfoLmp.MaxLengthObject + 10]; //??? 10 ??? MAGIC NUMBER!!!
    queries.StartTransaction();
    for(N_Obj = 1; N_Obj <= sInfoLmp.CoObjMax; N_Obj++)
    {
        sPassport = hFileHandler.GetPasp(N_Obj);
        lRetCode = hFileHandler.GetMetric(sPassport,pMetric);
        if(lRetCode < 0)
        {
           // printf(LMP_TO_DB_NAME" : INTERNAL_FILE_DESCRIPTOR_ERROR. GET PASSPORT//METRICS Position: %d Code: %d \n", N_Obj, lRetCode);
            bRetCode = false;
            break;
        }

        if(!queries.PushPassportAndMetrics(&sPassport, pMetric,sInfoLmp.MaxLengthObject + 10))
        {
            bRetCode = false;
            break;
        }
    }
    queries.EndTransaction();

	delete[] pMetric;
	pMetric = NULL;
	if(!bRetCode)
	{
		return LMP_TO_DB_INTERNAL_PASSPORT_METRIC_PUSH_ERROR;
	}

    return LMP_TO_DB_RETURN_CODE_SUCCESS;
}